import {Button, Form, Input, message, Modal, Popconfirm, Select, Table} from "antd";
import React, {Suspense, useEffect, useState, useTransition} from "react";
import {useDictCategory} from "../../Hooks";
import {MetaType, ModalType} from "../../util/publicType";
import {addDict, delDict, dictList, editDict} from "../../api";
import {AxiosResponse} from "axios";
import {ColumnsType} from "antd/es/table";
import moment from "moment";
import RequestLoading from "../../components/RequestLoading";

// 表数据接口
interface DataType {
    id: string,
    key: string,
    name: string,
    categoryName: string,
    created_at: number | string,
    fieldCategory: {
        id: string,
        name: string
    }
}

// 数据字典页面
const Dict = () => {
    const [loading, setTransition] = useTransition();
    // 搜索from
    const [searchForm] = Form.useForm();

    // dict表单
    const [dictForm] = Form.useForm();

    // 分类数据
    const {optionCategory} = useDictCategory();

    // 分页
    const [page, setPage] = useState<number>(1);
    // 当前页数
    const [size, setSize] = useState<number>(15);

    // 分页数据
    const [meta, setMeta] = useState<MetaType>({
        currentPage: 1,
        lastPage: 1,
        perSize: 1,
        total: 1
    });

    // 搜索参数name
    const [name, setName] = useState<string | null>(null);

    // 搜索参数分类
    const [typeId, setTypeId] = useState<string | null>(null);

    // 数据源
    const [data, setData] = useState<DataType[]>([]);

    // 弹窗控制
    const [modalState, setModalState] = useState<ModalType>({
        title: "新建用户",
        visible: false
    });

    // 当前数据
    const [currentData, setCurrentData] = useState<DataType | null>(null)


    // 表头
    const columns: ColumnsType<DataType> = [
        {
            title: "字典名称",
            dataIndex: "name",
            key: "name",
            align: "center"
        },
        {
            title: "字典分类",
            dataIndex: "categoryName",
            key: "categoryName",
            align: "center"
        },
        {
            title: "生成时间",
            dataIndex: "created_at",
            key: "created_at",
            align: "center"
        },
        {
            title: "操作",
            dataIndex: "id",
            key: "id",
            align: "center",
            render: (v: string, record: DataType) => {
                return (
                    <div>
                        <Button type="primary" onClick={() => editClick(record)}
                                style={{marginRight: "10px"}}>编辑</Button>
                        <Popconfirm
                            title="删除操作"
                            description={`确定删除${record.name}分类吗？`}
                            onConfirm={() => delClick(v)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="primary" danger>删除</Button>
                        </Popconfirm>
                    </div>
                )
            }
        }
    ]

    const getData = (page: number, size: number, typeId: string | null, name: string | null) => {
        setTransition(() => {
            dictList(page, size, typeId, name).then((r: AxiosResponse) => {
                const {meta, data} = r.data.data;
                setMeta(meta);
                setData(data.map((v: DataType) => {
                    return {
                        ...v,
                        categoryName: v.fieldCategory.name,
                        key: v.id,
                        created_at: moment((v.created_at as number) * 1000).format("YYYY-MM-DD HH:mm:ss")
                    }
                }));
            }, err => message.error(err));
        })
    }

    useEffect(() => {
        getData(page, size, typeId, name)
    }, [page, size, typeId, name])

    // 搜索完成
    const searchFinish = (v: { type_id: string, name: string }) => {
        if (!v.type_id) {
            setTypeId(null);
        } else {
            setTypeId(v.type_id)
        }
        if (!v.name) {
            setName(null)
        } else {
            setName(v.name)
        }
    }

    // 新建
    const addClick = () => {
        setModalState({
            title: "新建字典",
            visible: true
        });
        setCurrentData(null);
    }

    // 编辑
    const editClick = (v: DataType) => {
        dictForm.setFieldsValue(v);
        setModalState({
            title: "编辑分类",
            visible: true,
        });
        setCurrentData(v)
    }

    // 删除
    const delClick = (id: string) => {
        delDict(id).then(() => {
            getData(page, size, typeId, name);
            window.location.reload();
            message.success("删除成功");
        }, err => message.error(err));
    }

    // 字典表单完成
    const dictFinish = (v: { name: string, type_id: string }) => {
        let request: Promise<AxiosResponse>;
        if (currentData) {
            request = editDict(v, currentData.id)
        } else {
            request = addDict(v);
        }
        request.then(async () => {
            // 重置
            dictForm.resetFields();
            getData(page, size, typeId, name);
            setModalState(v => {
                return {
                    ...v,
                    visible: false
                }
            });
            window.location.reload();
            await message.success("操作成功");
        }, err => message.error(err))
    };
    return (
        <div>
            <div className="user-header">
                <Form form={searchForm} layout="inline" onFinish={searchFinish}>
                    <Form.Item
                        name="name"
                        label="名字"
                    >
                        <Input placeholder="请输入分类名字"/>
                    </Form.Item>
                    <Form.Item
                        name="type_id"
                        label="类型"
                    >
                        <Select
                            style={{width: "200px"}}
                            placeholder="请选择分类"
                            options={optionCategory}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" style={{marginRight: "10px"}} htmlType="submit">
                            搜索
                        </Button>
                        <Button type="primary" htmlType="reset" style={{marginRight: "10px"}}>
                            重置
                        </Button>
                        <Button type="primary" onClick={addClick}>
                            新建
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            {
                loading ? <RequestLoading/> : (
                    <Table columns={columns} dataSource={data} pagination={
                        {
                            current: meta.currentPage,
                            defaultCurrent: meta.currentPage,
                            defaultPageSize: meta.perSize,
                            pageSize: meta.perSize,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            showTotal: (t: number) => `总条数${t}`,
                            total: meta.total,
                            onChange: (page: number, perSize: number) => {
                                setPage(page)
                                setSize(perSize)
                            }
                        }
                    }/>
                )
            }
            <Modal title={modalState.title} open={modalState.visible} footer={null} onCancel={() => {
                setModalState(v => {
                    return {
                        ...v,
                        visible: false
                    }
                });
                dictForm.resetFields();
            }
            }>
                <Form form={dictForm} onFinish={dictFinish}>
                    <Form.Item
                        name="name"
                        label="名字"
                        rules={[{required: true, message: '请输入名字'}]}
                    >
                        <Input placeholder="请输入字典名字"/>
                    </Form.Item>
                    <Form.Item
                        name="type_id"
                        rules={[{required: true, message: '至少选择一项'}]}
                        label="类型"
                    >
                        <Select
                            style={{width: "200px"}}
                            placeholder="请选择分类"
                            options={optionCategory}
                        />
                    </Form.Item>
                    <Form.Item wrapperCol={{offset: 8, span: 16}}>
                        <Button type="primary" style={{marginRight: "10px"}} htmlType="submit">
                            提交
                        </Button>
                        <Button type="primary" htmlType="reset">
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default Dict;